package com.fc.captcha.autoconfigure;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 验证码服务类
 * 纯验证码生成服务，不包含存储和验证逻辑
 */
public class CaptchaService {

    private final CaptchaProperties properties;

    public CaptchaService(CaptchaProperties properties) {
        this.properties = properties;
    }

    /**
     * 生成验证码图片和对应code
     * @return Map包含code和imageBase64
     */
    public Map<String, Object> generateCaptcha() {
        // 1. 创建验证码对象
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(
                properties.getWidth(),
                properties.getHeight(),
                properties.getCodeLength(),
                properties.getLineCount()
        );

        // 2. 设置自定义字符生成器
        RandomGenerator randomGenerator = new RandomGenerator(properties.getCharBase(), properties.getCodeLength());
        captcha.setGenerator(randomGenerator);
        captcha.createCode();

        String code = captcha.getCode();

        // 3. 返回结果
        Map<String, Object> result = new HashMap<>(2);
        result.put("code", code);
        result.put("image", captcha.getImageBase64());

        return result;
    }

    /**
     * 生成验证码（包含唯一标识）
     * @return Map包含code、imageBase64和唯一标识
     */
    public Map<String, Object> generateCaptchaWithId() {
        Map<String, Object> result = generateCaptcha();
        result.put("id", UUID.randomUUID().toString().replace("-", ""));
        return result;
    }

    /**
     * 验证验证码（简单比较，不包含存储逻辑）
     * @param inputCode 用户输入的验证码
     * @param correctCode 正确的验证码
     * @return 是否验证成功
     */
    public boolean validate(String inputCode, String correctCode) {
        return inputCode != null && inputCode.equalsIgnoreCase(correctCode);
    }
}